import heapq
from collections import defaultdict
from collections import OrderedDict
# 1.4 找到最大或最小的N个元素
def test1_4():
	print('找到最大或最小的N个元素')
	nums = [1,8,2,23,7,-4,18,23,42,37,2]
	print("最大三个元素：",heapq.nlargest(3,nums))
	print("最小三个元素：",heapq.nsmallest(3,nums))

# 1.5 实现优先级队列
class PriorityQueue:
	def __init__(self):
		self._queue = []
		self._index = 0

	def push(self,item,priority):
		heapq.heappush(self._queue,(-priority,self._index,item))
		self._index+=1

	def pop(self):
		return heapq.heappop(self._queue)[-1]

class Item:
	def __init__(self,name):
		self.name = name
	def __repr__(self):
		return 'Item({!r})'.format(self.name)

def test1_5():
	print('实现优先级队列')
	q = PriorityQueue()
	q.push(Item('foo'),1)
	q.push(Item('bar'),5)
	q.push(Item('spam'),4)
	q.push(Item('grok'),1)
	print("q1:",q.pop())
	print("q2:",q.pop())
	print("q3:",q.pop())
	print("q4:",q.pop())

# 1.6 在字典中将键值映射到多个值上
def test1_6():
	print('在字典中将键值映射到多个值上')
	# collections.defaultdict实现
	d = defaultdict(list)
	d['a'].append(1)
	d['a'].append(2)
	d['b'].append(3)
	print("defaultdict(list): ",d)
	# regular dictionary
	e = {}
	e.setdefault('a',[]).append(10)
	e.setdefault('a',[]).append(-10)
	e.setdefault('b',[]).append(110)
	print("regular dictionary: ",e)

# 1.7 创建字典,同时对字典做序列化或迭代操作时，能够控制其中元素的顺序
def test1_7():
	print('实现有序字典')
	#OrderedDict 能够保证对字典迭代时，严格按照元素初始添加的顺序进行
	d = OrderedDict()
	d['foo'] = 1
	d['bar']=2
	d['spam']=3
	d['grok']=4
	for key in d:
		print("OrderedDict： "+key+" - "+str(d[key]))

# 1.8 与字典相关计算问题
def test1_8():
	print('与字典相关计算问题')
	prices = {
		'ACME':45.23,
		'AAPL':612.78,
		'IBM':205.55,
		'HPQ':37.20,
		'FB':10.75
	}
	# PS: zip()创建的迭代器，只能被使用一次，再次使用会报异常ValueError
	print('价格最低股票: ',min(zip(prices.values(),prices.keys())))
	print('价格最高股票: ',max(zip(prices.values(),prices.keys())))
	print('股票由低到高排序: ',sorted(zip(prices.values(),prices.keys())))
	print('如果value相同，会返回最大/最小的key做对比')
	temp ={
		'AAAA':42.35,
		'ZZZZ':42.35
	}
	print("max(zip()):  ",max(zip(temp.values(),temp.keys())))
	print("min(zip()):  ",min(zip(temp.values(),temp.keys())))

# 1.9 找出两个字典中，相同的地方（相同的键，相同的值）
def test1_9():
	print('111')
	
if __name__ == '__main__':
	test1_4()
	test1_5()
	test1_6()
	test1_7()
	test1_8()
	test1_9()
